const { exec } = require('../utils/mysqlUtils')
const jwt = require('jsonwebtoken')
class UserController {
    // 查询，带分页和字段
    async getUserList(ctx,next) {
        try {
            const currentPage = ctx.query.currentPage || 1
            const pageSize = ctx.query.pageSize || 10
            // search参数 
            const {name,rule,address,age,gender} = ctx.query
            let n = (currentPage - 1) * pageSize
            let sql = `select * from user where 1=1`  
            let tatalSql = `SELECT COUNT(*) AS total FROM user WHERE 1=1`

            if(rule) {
            sql += `AND like rule = '%${rule}%'`
            tatalSql += `AND rule='${rule}'`
            }
            if(address) {
            sql += `AND like address = '%${address}%'`
            tatalSql += `AND address='${age}'`
            }
            if(age) {
            sql += `AND like age = '%${age}%'`
            tatalSql += `AND age='${age}'`
            }
            if(name) {
            sql += `AND like name = '%${name}%'`
            tatalSql += `AND name='${name}'`
            }
            if(gender) {
            sql += `AND like gender = '%${gender}%'`
            tatalSql += `AND gender='${gender}'`
            }
            //   查list
            sql += ` limit ${n},${pageSize}`
            const res = await exec(sql)
            // 查总数
            const res1 = await exec(tatalSql)
            res.forEach(item => {
                delete item.password
            });
            ctx.success({data:res,total:res1[0].total,msg:'操作成功!'})
        } catch (error) {
        }
    }
    // 添加
    async addUser(ctx,next) {
        try {
            // 校验参数
            ctx.verifyParams({
                name: {required: true,type:'string'},
                password: {required: true,type:'string'},
                rule: {required: true,type:'number'},
                gender: {required: true,type:'number'}
            })
            // 校验账号
            const {name,password,rule,age,address,avatar,gender} = ctx.request.body
            console.log(name);
            const addName = await exec(`select name from user where name = '${name}'`)
            if(addName.length > 0 ) return  ctx.body = {code:201,data:null,msg:'姓名已存在'}
            // 选传参数 age,address
            const sql = `INSERT INTO user 
                            (name,password,rule,age,address,avatar,gender)
                            values
                            ('${name}','${password}','${rule}',${age || null},${address || null},${avatar || null},'${gender}')`
            // 添加
            await exec(sql) 
            ctx.success({data:null,msg:'添加成功', code:200})
            } catch (error) {
                    ctx.body = error.errors
                }
            }
    // 修改
    async changeUser(ctx,next) {
        try {
            const {name,age,password,address,rule,gender,avatar} = ctx.query
            if(!(ctx.query.id && name && age && password && address && rule && gender && avatar)) {
                const sql = `UPDATE user SET
                                 name = '${name}'
                                 age = '${age}' 
                                 password = '${password}' 
                                 address = '${address}' 
                                 rule = '${rule}' 
                                 gender = '${gender}' 
                                 avatar = '${avatar}' 
                                 WHERE id = '${ctx.query.id}'`
                await exec(sql)
                ctx.success({data:null,msg:'修改成功',code:200})
            } else {
                ctx.body = {code:0,data:'请传入用户id'}
            }
        } catch (error) {
            ctx.body = error
        }
    }
    // 删除
    async delUser(ctx,next) {
        try {
            if(ctx.query.id) {
                const sql = `DELETE FROM user WHERE id = ${ctx.query.id}`
                await exec(sql)
                ctx.success({data:null,code:200,msg:'删除成功！'})
            } else {
                ctx.body = {code:0,data:'请传入用户id'}
            }
        } catch (error) {
            ctx.body = error
        }
    }
    // 登录
    async login(ctx,next) {
        try {
            const {userName,password}= ctx.request.body; 
            
            const sql = `SELECT * FROM user WHERE name="${userName}" AND password="${password}"`
            const user = await exec(sql)
            if (!user) {
                ctx.body = {
                    code:401,
                    message: '账户或密码错误！',
                }
                return;
            }
            // 生成token
            const token = jwt.sign({id:user.id,userName:user.userName},'zjh666',{ expiresIn: 60 })
            delete user[0].password
            ctx.success({data:{...user[0],token},code:200,msg:'登录成功！'})
        } catch (error) {
            ctx.throw(500,error)
        }
    }
    // 头像上传
    async upload(ctx,next) {
        console.log(ctx.req.file); // 获取文件
        ctx.body = {
            code:200,
            msg: '上传成功',
            data: {
                path:ctx.req.file.path
            }
        }
    }
}
exports = module.exports  = new UserController()
